package com.lg.xxmall.product.service.impl;

import com.lg.xxmall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.common.utils.PageUtils;
import com.lg.common.utils.Query;

import com.lg.xxmall.product.dao.CategoryDao;
import com.lg.xxmall.product.entity.CategoryEntity;
import com.lg.xxmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 按照树形结构返回
     * */
    @Override
    public List<CategoryEntity> listWithTree() {

        //查询所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);

        //一级分类
        List<CategoryEntity> leve1 = list.stream().filter(categoryEntity ->{
            return categoryEntity.getParentCid() == 0 ;
        }).map((menu)->{
            menu.setChildren(getChildrens(menu,list));
            return menu;
        }).sorted((menu1,menu2)->{
            return  (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return leve1;
    }

    @Override
    public void removeMenveByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被引用。
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查询 所有分类的子分类
     * */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(info->{
            return info.getParentCid().equals(root.getCatId());
        }).map(info->{
            info.setChildren(getChildrens(info,all));
            return info;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return children;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId,paths);

        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths) {

        //收集当前节点ID
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);

        if (categoryEntity != null && categoryEntity.getParentCid() !=0) {
            findParentPath(categoryEntity.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 级联更新所有关联的数据
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        //todo 更新冗余字段数据一致
    }

}
